// 微信公众号、微信小程序、Android、iOS的应用权限、判断、打开应用权限设置界面、以及位置系统服务是否开启

// #ifdef H5
// 微信公众号权限授权
export function wxPublicPermissionAuth(options = {}, successCallback = () => {}, errCallback = () => {}) {
    if (jWeixin) {
        if (this.$api.auth.wxPublicPermissionAuth && typeof this.$api.auth.wxPublicPermissionAuth === 'function') {
            let url = window.location.href.split('#')[0];
            this.$api.auth.wxPublicPermissionAuth({
                url
            }).then(res => {
                // 微信SDK配置
                jWeixin.config({
                    debug: options.debug || false, // 调试模式
                    appId: res.appId, // 必填，公众号的唯一标识
                    timestamp: res.timestamp, // 必填，生成签名的时间戳
                    nonceStr: res.noncestr, // 必填，生成签名的随机串
                    signature: res.signature, // 必填，签名
                    jsApiList: options.jsApiList // 必填，需要使用的JS接口列表
                });
                successCallback();
            }).catch(err => {
                errCallback(err);
            })
        } else {
            uni.showToast({
                icon: 'none',
                title: '微信公众号权限授权接口未配置,请检查'
            });
            errCallback();
        }
    } else {
        uni.showToast({
            icon: 'none',
            title: "微信SDK未配置,请检查"
        });
        errCallback();
    }
}
// #endif

// #ifdef MP-WEIXIN
// 判断微信小程序位置权限
export function isOpenWxMpLocationPermission(successCallback = () => {}, errCallback = () => {}) {
    uni.getSetting({
        success: res => {
            if (res.authSetting['scope.userLocation']) {
                uni.getLocation({
                    type: 'gcj02',
                    success: res => {
                        successCallback(res);
                    },
                    fail: (err) => {
                        console.log("位置信息错误", err);
                        errCallback("位置信息获取失败");
                    }
                });
            } else {
                errCallback("“位置信息”未授权");
                uni.showModal({
                    title: '提示',
                    content: '请先在设置页面打开“位置信息”使用权限',
                    confirmText: '去设置',
                    cancelText: '再逛会',
                    success: res => {
                        if (res.confirm) {
                            uni.openSetting();
                        }
                    }
                });
            }
        }
    });
}
// #endif

// #ifdef APP-PLUS
const isIos = (plus.os.name == "iOS")
// 判断IOS推送权限
export function isOpenIosPushPermission() {
    let result = 0;
    let UIApplication = plus.ios.import("UIApplication");
    let app = UIApplication.sharedApplication();
    let enabledTypes = 0;
    if (app.currentUserNotificationSettings) {
        let settings = app.currentUserNotificationSettings();
        enabledTypes = settings.plusGetAttribute("types");
        if (enabledTypes == 0) {
            console.log("推送权限没有开启");
        } else {
            result = 1;
            console.log("已经开启推送功能!")
        }
        plus.ios.deleteObject(settings);
    } else {
        enabledTypes = app.enabledRemoteNotificationTypes();
        if (enabledTypes == 0) {
            console.log("推送权限没有开启!");
        } else {
            result = 1;
            console.log("已经开启推送功能!")
        }
        console.log("enabledTypes2:" + enabledTypes);
    }
    plus.ios.deleteObject(app);
    plus.ios.deleteObject(UIApplication);
    return result;
}


// 判断IOS定位权限是否开启
export function isOpenIosLocationPermission() {
    let result = 0;
    let cllocationManger = plus.ios.import("CLLocationManager");
    let status = cllocationManger.authorizationStatus();
    result = (status != 2) ? 1 : 0;
    if (result == 1) {
        console.log("已经开启定位权限");
    } else {
        console.log("定位权限没有开启");
    }
    // 以下代码判断了手机设备的定位是否关闭，推荐另行使用方法 checkSystemEnableLocation
    /* let enable = cllocationManger.locationServicesEnabled();
    let status = cllocationManger.authorizationStatus();
    console.log("enable:" + enable);
    console.log("status:" + status);
    if (enable && status != 2) {
    	result = true;
    	console.log("手机定位服务已开启且已授予定位权限");
    } else {
    	console.log("手机系统的定位没有打开或未给予定位权限");
    } */
    plus.ios.deleteObject(cllocationManger);
    return {
        result,
        permissionName: "定位"
    };
}

// 判断IOS麦克风权限是否开启
export function isOpenIosAudioPermission() {
    let result = 0;
    let avaudiosession = plus.ios.import("AVAudioSession");
    let avaudio = avaudiosession.sharedInstance();
    let permissionStatus = avaudio.recordPermission();
    if (permissionStatus == 1684369017 || permissionStatus == 1970168948) {
        console.log("麦克风权限没有开启");
    } else {
        result = 1;
        console.log("麦克风权限已经开启");
    }
    plus.ios.deleteObject(avaudiosession);
    return result;
    return {
        result,
        permissionName: "麦克风"
    };
}

// 判断IOS相机权限是否开启
export function isOpenIosCameraPermission() {
    let result = 0;
    let AVCaptureDevice = plus.ios.import("AVCaptureDevice");
    let authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');
    console.log("authStatus:" + authStatus);
    if (authStatus == 3) {
        result = 1;
        console.log("相机权限已经开启");
    } else {
        console.log("相机权限没有开启");
    }
    plus.ios.deleteObject(AVCaptureDevice);
    return {
        result,
        permissionName: "相机"
    };
}

// 判断IOS相册权限是否开启
export function isOpenIosAlbumPermission() {
    let result = 0;
    let PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
    let authStatus = PHPhotoLibrary.authorizationStatus();
    console.log("authStatus:" + authStatus);
    if (authStatus == 3) {
        result = 1;
        console.log("相册权限已经开启");
    } else {
        console.log("相册权限没有开启");
    }
    plus.ios.deleteObject(PHPhotoLibrary);
    return {
        result: result,
        permissionName: "相册"
    };
}

// 判断IOS通讯录权限是否开启
export function isOpenIosContactPermission() {
    let result = 0;
    let CNContactStore = plus.ios.import("CNContactStore");
    let cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);
    if (cnAuthStatus == 3) {
        result = 1;
        console.log("通讯录权限已经开启");
    } else {
        console.log("通讯录权限没有开启");
    }
    plus.ios.deleteObject(CNContactStore);
    return {
        result: result,
        permissionName: "通讯录"
    };
}

// 判断IOS日历权限是否开启
export function isOpenIosCalendarPermission() {
    let result = 0;
    let EKEventStore = plus.ios.import("EKEventStore");
    let ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0);
    if (ekAuthStatus == 3) {
        result = 1;
        console.log("日历权限已经开启");
    } else {
        console.log("日历权限没有开启");
    }
    plus.ios.deleteObject(EKEventStore);
    return {
        result: result,
        permissionName: "日历"
    };
}

// 判断备忘录权限是否开启
export function isOpenIosMemoPermission() {
    let result = 0;
    let EKEventStore = plus.ios.import("EKEventStore");
    let ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1);
    if (ekAuthStatus == 3) {
        result = 1;
        console.log("备忘录权限已经开启");
    } else {
        console.log("备忘录权限没有开启");
    }
    plus.ios.deleteObject(EKEventStore);
    return {
        result: result,
        permissionName: "备忘录"
    };
}

// Android权限查询
export function requestAndroidPermission(permissionID, permissionName) {
    return new Promise((resolve, reject) => {
        plus.android.requestPermissions(
            [permissionID], // 理论上支持多个权限同时查询，但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
            function(resultObj) {
                let result = 0;
                for (let i = 0; i < resultObj.granted.length; i++) {
                    let grantedPermission = resultObj.granted[i];
                    console.log('已获取的权限：' + grantedPermission);
                    result = 1
                }
                for (let i = 0; i < resultObj.deniedPresent.length; i++) {
                    let deniedPresentPermission = resultObj.deniedPresent[i];
                    console.log('拒绝本次申请的权限：' + deniedPresentPermission);
                    result = 0
                }
                for (let i = 0; i < resultObj.deniedAlways.length; i++) {
                    let deniedAlwaysPermission = resultObj.deniedAlways[i];
                    console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
                    result = -1
                }
                resolve({
                    result: result,
                    permissionName: permissionName
                });
                // 若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
                // if (result != 1) {
                // gotoAppPermissionSetting()
                // }
            },
            function(error) {
                console.log('申请权限错误：' + error.code + " = " + error.message);
                resolve({
                    code: error.code,
                    message: error.message
                });
            }
        );
    });
}

// 判断应用权限是否开启
export function isOpenPermission(permissionID, callback) {
    function handle(res) {
        callback && callback(res.result);
        if (res.result === -1) {
            uni.showModal({
                title: "提示",
                content: "您还未开启" + res.permissionName + "权限,是否去应用设置里开启~",
                confirmText: "去开启",
                cancelText: "再等等",
                success: (data) => {
                    if (data.confirm) {
                        gotoAppPermissionSetting();
                    }
                }
            });
        }
    }
    if (permissionID == "location") { // 位置
        if (isIos) {
            handle(isOpenIosLocationPermission());
        } else {
            requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION", "位置").then(handle);
        }
    } else if (permissionID == "camera") { // 摄像头
        if (isIos) {
            handle(isOpenIosCameraPermission());
        } else {
            requestAndroidPermission("android.permission.CAMERA", "摄像头").then(handle);
        }
    } else if (permissionID == "photoLibrary") { // 相册
        if (isIos) {
            handle(isOpenIosAlbumPermission());
        } else {
            requestAndroidPermission("android.permission.READ_EXTERNAL_STORAGE", "相册读取").then(handle);
        }
    } else if (permissionID == "record") { // 麦克风
        if (isIos) {
            handle(isOpenIosAudioPermission());
        } else {
            requestAndroidPermission("android.permission.RECORD_AUDIO", "麦克风").then(handle);
        }
    } else if (permissionID == "push") { // 推送
        if (isIos) {
            handle(isOpenIosPushPermission());
        } else {
            handle(1);
        }
    } else if (permissionID == "contact") { // 通讯录
        if (isIos) {
            handle(isOpenIosContactPermission());
        } else {
            requestAndroidPermission("android.permission.READ_CONTACTS", "通讯录读取").then(handle);
        }
    } else if (permissionID == "calendar") { // 日历
        if (isIos) {
            handle(isOpenIosCalendarPermission());
        } else {
            requestAndroidPermission("android.permission.READ_CALENDAR", "日历读取").then(handle);
        }
    } else if (permissionID == "memo") { // 备忘录
        if (isIos) {
            handle(isOpenIosMemoPermission());
        } else {
            handle(1);
        }
    } else if (permissionID == "call_phone") { // 拨打电话
        if (isIos) {
            handle(1);
        } else {
            requestAndroidPermission("android.permission.CALL_PHONE", "拨打电话").then(handle);
        }
    }
}

// 跳转到应用的权限页面
export function gotoAppPermissionSetting() {
    if (isIos) {
        let UIApplication = plus.ios.import("UIApplication");
        let application2 = UIApplication.sharedApplication();
        let NSURL2 = plus.ios.import("NSURL");
        // let setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");
        let setting2 = NSURL2.URLWithString("app-settings:");
        application2.openURL(setting2);

        plus.ios.deleteObject(setting2);
        plus.ios.deleteObject(NSURL2);
        plus.ios.deleteObject(application2);
    } else {
        // console.log(plus.device.vendor);
        let Intent = plus.android.importClass("android.content.Intent");
        let Settings = plus.android.importClass("android.provider.Settings");
        let Uri = plus.android.importClass("android.net.Uri");
        let mainActivity = plus.android.runtimeMainActivity();
        let intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        let uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
        intent.setData(uri);
        mainActivity.startActivity(intent);
    }
}

// 检查系统的设备服务是否开启
export function checkSystemEnableLocation() {
    if (isIos) {
        let result = false;
        let cllocationManger = plus.ios.import("CLLocationManager");
        result = cllocationManger.locationServicesEnabled();
        console.log("系统定位开启:" + result);
        plus.ios.deleteObject(cllocationManger);
        return result;
    } else {
        let context = plus.android.importClass("android.content.Context");
        let locationManager = plus.android.importClass("android.location.LocationManager");
        let main = plus.android.runtimeMainActivity();
        let mainSvr = main.getSystemService(context.LOCATION_SERVICE);
        let result = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
        console.log("系统定位开启:" + result);
        return result
    }
}
// #endif
